<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件路径" prop="downloadLink">
        <el-input
          v-model="queryParams.downloadLink"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="适配设备" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:firmware:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:firmware:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:firmware:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:firmware:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="firmwareList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id" v-if="true"/>
      <el-table-column label="版本号" align="center" prop="version"/>
      <el-table-column label="文件路径" align="center" prop="downloadLink"/>
      <el-table-column label="适配设备" align="center" prop="deviceName"/>
      <el-table-column label="说明" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="filePage(scope.row)"
          >查看固件
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:firmware:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:firmware:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改固件管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <span style="display: inline-block; margin-left:72px;color:red; font-size: small;">版本号默认为0.0.0格式</span>
        <span style="display: inline-block; margin-left:72px;color:red; font-size: small;" v-if="this.title === '修改固件管理'">要求 版本号>=原版本号</span>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="文件路径" prop="downloadLink">
          <el-select v-model="aDownloadLink" placeholder="请选择或其他" style="width:30%" @change="linkChange()">
            <el-option v-for="(item, index) in downloadLinkList" :key="index" :label="item" :value="item"></el-option>
            <el-option value="其 他">其 他</el-option>
          </el-select>
          <el-input style="width:60%; float:right;" v-if="aDownloadLink === '其 他'"
                    v-model="form.downloadLink"></el-input>
        </el-form-item>
        <el-form-item label="适配设备" prop="deviceId">
          <el-select v-model="form.deviceId" placeholder="请选择">
            <el-option v-for="item in deviceList" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="固件文件" :visible.sync="filePageOpen" width="500px" append-to-body>
      <el-form label-width="80px">
        <span style="display: inline-block; margin-left:72px;color:#d24242; font-size: medium;" v-if="file !== undefined">点击“上传”更新当前版本固件</span>
        <span style="display: inline-block; margin-left:72px;color:#d24242; font-size: medium;" v-else>该版本无可用固件，待上传</span>
        <el-form-item label="固件录入">
          <input type="file" style="display: inline-block; width: 50%;" name="file" id="fileInput" ref="fileInput" required="true" message="不能为空" trigger="blur" @change="handleFileChange">
          <label style="display: inline-block;width: 10%;" for="remark">备注</label>
          <input style="display: inline-block;width: 38%;" type="text" v-model="remark" id="remark">
        </el-form-item>
        <el-form-item label="历史固件">
          <el-button :loading="buttonLoading" @click="getFirmwareHistory()" type="primary">下载固件git记录</el-button>
          <el-button :loading="buttonLoading" @click="openFirmwareHistory()" type="primary" style="float:right; margin-right:30px;">版本内容对比</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: space-between;">
        <div>
          <el-button :loading="buttonLoading" @click="downloadFile(file)" type="primary">下 载</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="uploadSubmit">上 传</el-button>
        </div>
<!--        <el-button :loading="buttonLoading" @click="getFirmwareHistory()" type="primary">历史固件</el-button>-->
        <el-button @click="fileCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="固件历史信息" :visible.sync="historyOpen" width="800px" append-to-body>
      <el-table :data="firmwareHistory" :row-style="{ height: '100px' }">
        <el-table-column label="id" align="center" prop="commitId"/>
        <el-table-column label="remark" align="center" prop="message"/>
        <el-table-column label="date" align="center" prop="date"/>
        <el-table-column label="diff" align="center" prop="diff" show-overflow-tooltip/>
        <el-table-column label="message" align="center" prop="message"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="historyDownload(scope.row)"
            >下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFirmware,
  getFirmware,
  delFirmware,
  addFirmware,
  updateFirmware,
  uploadFirmware,
  getFile,
  gitInfo
} from "@/api/system/firmware";
import {listDevice, getDevice} from "@/api/system/device"

export default {
  name: "Firmware",
  data() {
    return {
      historyOpen: false,
      firmwareHistory:[],
      remark: "",
      oldVersion: undefined,
      path: undefined,
      filePageOpen: false,
      file: undefined,
      aDownloadLink: '',
      downloadLinkList: [],
      deviceList: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 固件管理表格数据
      firmwareList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        version: undefined,
        downloadLink: undefined,
        deviceName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          {required: false}
        ],
        version: [
          {required: true, validator: this.validateVersion, trigger: "blur"}
        ],
        downloadLink: [
          {required: true, message: "文件路径不能为空", trigger: "blur"}
        ],
        deviceId: [
          {required: true, message: "适配设备不能为空", trigger: "blur"}
        ],
        remark: [
          {required: false}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeviceList();
  },
  methods: {
    historyDownload(row) {
      getFile(this.path + '/' + this.row.deviceName + '.bin', row.commitId)
        .then(response => {
          if (response.size !== 0) {
            const file = new File([response], row.deviceName + ".bin", {type: response.type});
            this.downloadFile(file);
          }
        }).catch(error => {
        alert("提交失败!")
      });
    },
    openFirmwareHistory() {
      this.historyOpen = true;
      gitInfo(this.path + '/' + this.row.deviceName + '.bin')
        .then(response => {
          this.firmwareHistory = response;
        })
    },
    getFirmwareHistory() {
      gitInfo(this.path + '/' + this.row.deviceName + '.bin')
        .then(response => {
          this.firmwareHistory = response;
          const data = JSON.stringify(response);
          const blob = new Blob([data], { type: 'application/json' });
          const file = new File([blob], "git日志文件.txt");
          this.downloadFile(file);
        })
    },
    /** 正则表达式验证version的格式，保证为0.0.0 **/
    validateVersion(rule, value, callback) {
      // 使用正则表达式验证格式
      const regex = /^\d+\.\d+\.\d+$/;
      if (!regex.test(value)) {
        callback(new Error('请输入正确的版本号格式，如0.0.0'));
      }
      if (this.oldVersion !== undefined) {
        var newVersion = value.split('.').join('');
        var oldVersion = this.oldVersion.split('.').join('');
        if (newVersion < oldVersion) {
          callback(new Error('要求 版本号>=原版本号'));
        }
      }
      callback();
    },
    /** 查询固件管理列表 */
    getList() {
      this.loading = true;
      listFirmware(this.queryParams).then(response => {
        const promises = response.rows.map(item => {
          return getDevice(item.deviceId).then(response => {
            item.deviceName = response.data.name;
            return item;
          });
        });
        Promise.all(promises).then(updatedRows => {
          if (this.queryParams.deviceName !== undefined) {
            updatedRows = updatedRows.filter(item => item.deviceName.includes(this.queryParams.deviceName));
          }
          this.firmwareList = updatedRows;
          this.total = response.total;
          this.loading = false;
          this.downloadLinkList = updatedRows.map(item => {
            return item.downloadLink;
          });
          this.downloadLinkList = [...new Set(this.downloadLinkList.map(item => item))];
        });
      });
    },
    getDeviceList() {
      listDevice().then(response => {
        this.deviceList = response.rows.map(item => {
          return {
            value: item.id,
            label: item.name,
          };
        });
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        version: undefined,
        downloadLink: undefined,
        deviceId: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // -----上传固件-------
    /* 打开查看固件页面 */

    // -------下载固件-------
    downloadFile(file) {
      if (file === undefined) {
        alert("该版本无可用固件，待上传");
        return;
      }
      console.log("file:", file);
      const url = window.URL.createObjectURL(file); // 将File对象转换为URL地址

      const link = document.createElement('a'); // 创建<a>标签
      link.href = url; // 设置下载链接
      link.download = file.name; // 设置下载文件名
      link.style.display = 'none'; // 隐藏<a>标签

      document.body.appendChild(link); // 将<a>标签添加到文档中
      link.click(); // 模拟点击<a>标签，触发下载

      document.body.removeChild(link); // 下载完成后，移除<a>标签
      window.URL.revokeObjectURL(url); // 释放URL对象
    },
    getThisFile(row) {
      this.path = row.downloadLink + '/' + row.deviceName + '.bin';
      getFile(this.path)
        .then(response => {
          if (response.size !== 0) {
            const file = new File([response], row.deviceName + ".bin", { type: response.type });
            if (this.file === undefined) {
              this.file = file;
            } else {
              this.$set(this.file, file);
            }
          }
          this.filePageOpen = true;
        })
    },
    filePage(row) {
      this.file = undefined;
      this.getThisFile(row);
      this.row = row;
      this.path = row.downloadLink;
    },
    /* 上传文件 */
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.$refs.fileInput.value = "";
    },
    /* 确定上传文件 */
    uploadSubmit() {
      this.loading = true;
      if (this.file !== undefined) {
        // if (this.file.name === this.row.deviceName + '_' + this.row.version + '.bin') {
        //   alert('该版本号固件已存在，请更新固件信息');
        //   return;
        // }
        uploadFirmware(this.file, this.path, this.row.deviceName, this.remark, this.row.version)
          .then(result => {
            alert("提交成功!")
          })
          .catch(error => {
            alert("提交失败!")
          });
        this.loading = false;
        this.filePageOpen = false;
        this.row = undefined;
        this.firmwareHistory = [];
        this.remark = "";
      } else {
        alert("请选择文件!");
      }
    },
    /* 取消上传文件 */
    fileCancel() {
      this.firmwareHistory = [];
      this.filePageOpen = false;
      this.remark = "";
    },

    /* 文件存放路径修改 */
    linkChange() {
      if (this.aDownloadLink !== '其 他') {
        this.form.downloadLink = this.aDownloadLink;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getDeviceList();
      this.reset();
      this.form.version = "0.0.0";
      if (this.deviceList.length !== 0) {
        this.form.deviceId = this.deviceList[0].value;
        this.form.deviceName = this.deviceList[0].label;
      }
      if (this.downloadLinkList.length !== 0) {
        this.form.downloadLink = this.downloadLinkList[0];
      }
      this.open = true;
      this.title = "添加固件管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      this.getDeviceList();
      getFirmware(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.oldVersion = this.form.version;
        this.aDownloadLink = this.form.downloadLink;
        this.open = true;
        this.title = "修改固件管理";
      });
    },
    //TODO 版本号可手动改动，路径改为 路径+deviceName.bin
    /** 提交按钮 */
    submitForm() {
      const regex = /^[^\\\/:*?"<>|]+$/;
      if (!regex.test(this.form.filename) || !regex.test(this.form.downloadLink)) {
        alert("请规范填写文件名或文件路径");
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateFirmware(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            if (this.form.version === "" || this.form.version === undefined) {
              this.form.version = "0.0.0";
            }
            addFirmware(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
      this.reset();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除固件管理编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delFirmware(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/firmware/export', {
        ...this.queryParams
      }, `firmware_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
